package com.guaniu.voip.ui.login;

import android.Manifest;
import android.app.Activity;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.guaniu.voip.BaseActivity;
import com.guaniu.voip.R;
import com.guaniu.voip.sip.SipManager;
import com.guaniu.voip.ui.LauncherActivity;
import com.guaniu.voip.ui.main.MainActivity;
import com.guaniu.voip.utils.AppConstant;
import com.guaniu.voip.utils.SPUtils;
import com.guaniu.voip.utils.Utils;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import net.gotev.sipservice.BroadcastEventReceiver;
import net.gotev.sipservice.MediaState;

public class LoginActivity extends BaseActivity implements BroadcastEventReceiver.SipEventObserver{

    private QMUITopBarLayout mTopBar;

    public static final int PERMISSIONS_REQUEST_CODE = 10;
    public static final String[] PERMISSIONS_REQUIRED = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);

        initView();
        //请求权限
        ActivityCompat.requestPermissions(this, PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //初始化voip监听
        BroadcastEventReceiver.registerEventObserver(this, this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        BroadcastEventReceiver.getBroadcastEventReceiver().unRegisterEventObserverInner(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BroadcastEventReceiver.getBroadcastEventReceiver().unregister(this);
    }

    private void initView() {
        mTopBar = findViewById(R.id.topbar);
        mTopBar.setTitle("登录SIP服务器");
        EditText sip_accout_v = findViewById(R.id.user_name);
        EditText sip_pass_v = findViewById(R.id.password);
        EditText sip_server_v = findViewById(R.id.server_ip);
        EditText server_port_v = findViewById(R.id.server_port);

        String sip_number = SPUtils.getInstance().getString(AppConstant.SP_SIP_NUMBER);
        if (!Utils.isSpace(sip_number)) {
            sip_accout_v.setText(sip_number.trim());
        }
        String sip_pass = SPUtils.getInstance().getString(AppConstant.SP_SIP_PASSWORD);
        if (!Utils.isSpace(sip_pass)) {
            sip_pass_v.setText(sip_pass.trim());
        }
        String sip_server = SPUtils.getInstance().getString(AppConstant.SP_SIP_SERVER);
        if (!Utils.isSpace(sip_server)) {
            sip_server_v.setText(sip_server.trim());
        }
        int sip_server_port = SPUtils.getInstance().getInt(AppConstant.SP_SIP_PORT);
        server_port_v.setText(String.valueOf(sip_server_port));
        findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EditText sip_accout_v = findViewById(R.id.user_name);
                EditText sip_pass_v = findViewById(R.id.password);
                EditText sip_server_v = findViewById(R.id.server_ip);
                EditText server_port_v = findViewById(R.id.server_port);
                String sip_acc = sip_accout_v.getText().toString();
                if (Utils.isSpace(sip_acc)){
                    Toast.makeText(LoginActivity.this, "请输入SIP账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                String sip_pass = sip_pass_v.getText().toString();
                if (Utils.isSpace(sip_pass)){
                    Toast.makeText(LoginActivity.this, "请输入SIP密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                String sip_server = sip_server_v.getText().toString();
                if (Utils.isSpace(sip_server)){
                    Toast.makeText(LoginActivity.this, "请输入SIP服务器", Toast.LENGTH_SHORT).show();
                    return;
                }
                String sip_port = server_port_v.getText().toString();
                if (Utils.isSpace(sip_port)){
                    Toast.makeText(LoginActivity.this, "请输入SIP服务器端口", Toast.LENGTH_SHORT).show();
                    return;
                }
                showLoading("登录中...");
                //注册voip
                SipManager.getInstance().saveNewAccount(LoginActivity.this, sip_acc.trim(), sip_pass.trim(), sip_server.trim(), Integer.valueOf(sip_port));
            }
        });
    }

    @Override
    public void notifyRegState(String account, int code, String reason, long expiration) {
        hideLoading();
        if (code == 200) {
            //
            SipManager.getInstance().setRegState(account, SipManager.SIP_REG_ONLINE);
            //showError("登录成功");
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);//WebViewActivity
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 该Flag相当于Activity启动模式中的singleTask
            startActivity(intent);
            finish();
        }else{

            SipManager.getInstance().setRegState(account, SipManager.SIP_REG_OFFLINE);
            showError("登录失败，请检查用户名、密码和服务器IP");
        }
    }

    @Override
    public void notifyIncomingCall(String accountID, int callID, String displayName, String remoteUri, boolean isVideo) {

    }

    @Override
    public void notifyCallState(String accountID, int callID, int callStateCode, int callStatusCode, long connectTimestamp) {

    }

    @Override
    public void notifyCallMediaState(String accountID, int callID, MediaState stateType, boolean stateValue) {

    }

    @Override
    public void notifyChangeNetwork() {

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode != PERMISSIONS_REQUEST_CODE) {
            showError("请在设置中容许相应权限！");

        }
    }
}